package com.example.featuresdk.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.featuresdk.vo.Status
import kotlinx.coroutines.launch
import kotlin.coroutines.cancellation.CancellationException

open class BasicViewModel : ViewModel(){

    val basicState = BasicState()

    fun launch(action: suspend ()->Unit){
        viewModelScope.launch {
            try {
                action()
            }catch (e: CancellationException){
                //ignore
            }
            catch (t: Throwable){
                onError(t)
                Log.e("${this@BasicViewModel}","Error",t)
            }
        }
    }

    open fun onError(t: Throwable){
        basicState.status.value = Status.Error
        basicState.message.value = t.message?:""
    }
}